//依赖模块
var fs = require('fs');
var request = require("request");
var cheerio = require("cheerio");
var mkdirp = require('mkdirp');
 
//目标网址
var url = 'https://bshop.guanmai.cn/v587/?cms_key=hmjzc#/product?first_id=A1653&_k=ufauos';
 
//本地存储目录
var dir = './images';
 
//创建目录
mkdirp(dir, function(err) {
    if(err){
        console.log(err);
    }
});
 
//发送请求
request(url, function(error, response, body) {
    if(!error && response.statusCode == 200) {
        var $ = cheerio.load(body);
        $('.b-product-item-box .b-product-item-img img').each(function() {
            var src = $(this).attr('src');
            var name=$(this).parent().next().find(".b-product-item-name").text()
            console.log('正在下载' + src);
            download(src, dir, name);
            console.log('下载完成');
        });
    }
});
 
//下载方法
var download = function(url, dir, filename){
    request.head(url, function(err, res, body){
        request(url).pipe(fs.createWriteStream(dir + "/" + filename));
    });
};